
package com.monlyu.bo;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.SetUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.google.common.collect.Sets;
import com.monlyu.bean.Page;
import com.monlyu.bean.Pages;
import com.monlyu.util.LogUtil;
import com.monlyu.util.PermissUtil;
import com.monlyu.util.StringUtil;
import com.monlyu.util.WebOptUtil;
import com.monlyu.vo.Permission;
import com.monlyu.vo.Role;
import com.monlyu.vo.Role2Permission;
import com.monlyu.vo.User2Role;

/*******************************************************************************
 * <b>功能描述☞</b>关于角色对数据库的非查询查找操作,均包含在这个类中<br>
 * <b>开发公司☞</b>重庆唯尼科技有限公司<br>
 * <b>版权☞</b>本文件归重庆唯尼科技有限公司所有<br>
 * <b>项目名☞</b>monlyu<br>
 * <b>文件路径☞</b>com.monlyu.bo.RoleBo.java<br>
 * <b>开发日期☞</b>2010-1-13 <br>
 * 
 * @author monlyu
 * @since JDK 5
 * @version : 1.0.5
 ******************************************************************************/
@Repository(value = "roleBo")
public class RoleBo extends BaseBo {

    /** 获取所有的类 */
    public Pages<Role> findRoles(Page page){
        Criteria criteria = dao.initCriteria(Role.class);
        return buildPages(page, criteria, "name", "desc");
    }

    /**
     * 通过用户的ID获取用户的权限
     * 
     * @param 用户ID
     * @author monlyu
     * @since 2010-2-1
     */
    public Set<String> getPermissionByUId(Long userId){
        if (WebOptUtil.APP_ARGS.isDebug()) {
            LogUtil.log(RoleBo.class).debug("如果现实出本消息,说明系统的权限尚未启用,如果需要启动,请修改InitArgsData.xml中的devModel为false");
            Set<String> allSet = Sets.newHashSet();
            for (Permission p : getPermiss()) {
                allSet.add(p.getId());
            }
            return allSet;
        } else {
            List<User2Role> u2r = (List<User2Role>) dao.find("from com.monlyu.vo.User2Role u where u.userId=?", userId);
            if (u2r.isEmpty()) {
                return SetUtils.EMPTY_SET;
            }
            Set<String> setStr = Sets.newHashSet();
            for (Iterator<User2Role> iterator = u2r.iterator(); iterator.hasNext();) {
                Long roleId = iterator.next().getRoleId();
                List<Role2Permission> r2ps = dao.find(Role2Permission.class, "roleId", roleId);
                if (r2ps == null) {
                    return SetUtils.EMPTY_SET;
                }
                for (Role2Permission permiss : r2ps) {
                    setStr.add(permiss.getPermissionId());
                }
            }
            return setStr;
        }
    }

    /**
     * 获取所有的权限列表
     */
    public List<Permission> getPermiss(){
        Criteria criteria = dao.initCriteria(Permission.class);
        criteria.addOrder(Order.asc("type"));
        criteria.addOrder(Order.asc("order"));
        return criteria.list();
    }

    /**
     * 获取角色对应的权限List
     */
    public List<Role2Permission> getPermByRId(Long roleId){
        String hql = "from com.monlyu.vo.Role2Permission r where r.roleId=?";
        return dao.find(hql, roleId);
    }

    /**
     * 保存角色信息
     */
    public void save(Role role, String[] permiss){
        dao.insertOrUpdate(role);
        Long roleId = role.getId();
        clearCache(roleId);// 刷新缓存
        dao.delete(getPermByRId(role.getId()));
        if (permiss != null) {
            for (String pn : permiss) {
                Role2Permission r2p = new Role2Permission();
                r2p.setRoleId(roleId);
                r2p.setPermissionId(pn);
                dao.save2key(r2p);
            }
        }
    }

    // 清空缓存
    private void clearCache(Long roleId){
        List<User2Role> user2Roles = dao.find(User2Role.class, "roleId", roleId);
        for (User2Role user2Role : user2Roles) {
            PermissUtil.clearCache(user2Role.getUserId());
        }
    }

    /**
     * 获取所有的角色列表
     * 
     * @since 2010-2-11
     */
    public List<Role> getRollList(){
        return dao.find(Role.class);
    }

    /**
     * 根据用户的ID获取
     * 
     * @since 2010-2-11
     */
    public List<User2Role> getRoleByUid(Long uid){
        Criteria criteria = dao.initCriteria(User2Role.class);
        criteria.add(Restrictions.eq("userId", uid));
        return criteria.list();
    }

    /**
     * 检查是否有作某个事情的权限
     * 
     * @since 2010-2-17
     */
    public boolean checkPermission(String misson){
        if (StringUtil.isTrimEmpty(misson)) {
            return false;
        }
        final Set<String> pes = getPermissionByUId(curUser().getId());
        for (String p : pes) {
            if (p.trim().equals(misson.trim())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取当前用户的角色信息
     */
    public List<User2Role> getRole(){
        return getRoleByUid(curUser().getId());
    }
}
